package feces.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import feces.model.Storehouse;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * 获取所有库房
 * 
 * @author Bromine0x23
 */
@WebServlet(name = "storehouses", urlPatterns = {"/api/storehouses"})
@NoArgsConstructor
public class StorehousesServlet extends RESTfulServlet {
	
	/**
	 * 字典
	 * 
	 * @author Bromine0x23
	 */
	@NoArgsConstructor(access = AccessLevel.PROTECTED)
	protected static class Dictionary extends RESTfulServlet.Dictionary {
		public static final String MAIN = "main";
		
		public static final String SUB = "sub";
	}

	private static final long serialVersionUID = 4184850032219711886L;

	/**
	 * 响应GET请求
	 * 默认返回所有库房
	 * 当带有main参数时返回所有中心库房
	 * 当带有sub参数时返回所有中心库房
	 * 
	 * @return 满足条件的库房
	 */
	@Override
	protected Response<List<Storehouse>> responseRead(
		HttpServletRequest request,
		HttpServletResponse response
	) throws ServletException, IOException {
		if (request.getParameter(Dictionary.MAIN) != null) {
			return succeed(executeNamedQuery("Storehouse.findType", Storehouse.class, Storehouse.Type.MAIN));
		}
		if (request.getParameter(Dictionary.SUB) != null) {
			return succeed(executeNamedQuery("Storehouse.findType", Storehouse.class, Storehouse.Type.SUB));
		}
		return succeed(findAll(Storehouse.class));
	}
}
